const mysql = require('mysql2/promise')
const bcrypt = require('bcrypt')

const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'GKL9512357',
  database: 'novel_platform',
  charset: 'utf8mb4'
}

async function updateQQAdmin () {
  let connection
  try {
    connection = await mysql.createConnection(dbConfig)

    const email = '1477042095@qq.com'
    const newPassword = 'GKL9512357'
    const role = 'admin'

    console.log(`🔄 更新QQ账号为管理员...`)

    // 首先检查用户是否存在
    const [users] = await connection.execute(
      'SELECT id, username, email, role FROM users WHERE email = ?',
      [email]
    )

    if (users.length === 0) {
      console.log('❌ 用户不存在')
      return
    }

    const user = users[0]
    console.log(`📧 找到用户: ${user.email} (ID: ${user.id})`)

    // 加密新密码
    console.log('🔐 加密新密码...')
    const saltRounds = 10
    const passwordHash = await bcrypt.hash(newPassword, saltRounds)

    // 更新密码和角色
    console.log('🛡️ 更新为管理员权限...')
    await connection.execute(
      'UPDATE users SET password_hash = ?, role = ?, updated_at = NOW() WHERE email = ?',
      [passwordHash, role, email]
    )

    console.log('✅ 更新成功！')

    // 验证更新
    const [updatedUser] = await connection.execute(
      'SELECT id, username, email, nickname, role, status, level, coins, is_vip, created_at, updated_at FROM users WHERE email = ?',
      [email]
    )

    if (updatedUser.length > 0) {
      const userInfo = updatedUser[0]
      console.log('\n📋 更新后的用户信息:')
      console.log(`🆔 ID: ${userInfo.id}`)
      console.log(`👤 用户名: ${userInfo.username}`)
      console.log(`📧 邮箱: ${userInfo.email}`)
      console.log(`📛 昵称: ${userInfo.nickname}`)
      console.log(`🛡️ 角色: ${userInfo.role}`)
      console.log(`📊 状态: ${userInfo.status}`)
      console.log(`💰 金币: ${userInfo.coins}`)
      console.log(`⭐ VIP: ${userInfo.is_vip ? '是' : '否'}`)
      console.log(`🔑 密码: ${newPassword}`)
      console.log(`📅 创建时间: ${userInfo.created_at}`)
      console.log(`🔄 更新时间: ${userInfo.updated_at}`)
    }
  } catch (error) {
    console.error('❌ 错误:', error.message)
  } finally {
    if (connection) await connection.end()
  }
}

updateQQAdmin()
